<!DOCTYPE html>
<html lang="zh-CN" xmlns:th="http://www.thymeleaf.org">
<head>
<!--    <meta http-equiv="refresh" content="10">-->
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>管理员后台 - 局域网通讯系统</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/css/bootstrap.min.css" rel="stylesheet">
    <link rel="stylesheet" href="/css/login.css">
    <link rel="icon" type="image/png" href="/Image/logo.png">
    <style>
        body { background: linear-gradient(120deg, #e0e7ff 0%, #f1f5f9 100%); }
        .admin-header {
            display: flex;
            align-items: center;
            justify-content: space-between;
            padding: 24px 0 12px 0;
        }
        .admin-header .logo {
            height: 48px;
            margin-right: 18px;
        }
        .admin-title {
            font-size: 2.1rem;
            font-weight: 700;
            color: #2563eb;
            letter-spacing: 2px;
        }
        .admin-logout {
            position: fixed;
            top: 32px;
            right: 48px;
            z-index: 100;
            border-radius: 50px;
            box-shadow: 0 2px 8px rgba(80,120,200,0.13);
            font-size: 16px;
            font-weight: 600;
            padding: 8px 28px;
            background: #fff;
            color: #d32f2f;
            border: 2px solid #d32f2f;
            transition: background 0.2s, color 0.2s, box-shadow 0.2s;
        }
        .admin-logout:hover {
            background: #d32f2f;
            color: #fff;
            box-shadow: 0 4px 16px rgba(211,47,47,0.18);
            border-color: #d32f2f;
        }
        .admin-card {
            border-radius: 18px;
            box-shadow: 0 8px 32px rgba(80,120,200,0.13);
            background: #fff;
            padding: 32px 28px 28px 28px;
            margin-bottom: 32px;
        }
        .notice-area h5 {
            color: #2563eb;
            font-weight: 600;
        }
        .admin-table th, .admin-table td { vertical-align: middle; }
        .admin-table .btn-danger { padding: 6px 18px; font-size: 15px; }
        .notice-area { margin-bottom: 24px; }
        .btn-primary, .btn-danger { font-size: 16px; font-weight: 600; border-radius: 10px; }
        .admin-user { font-size: 1.1rem; color: #64748b; }
        /* 新增美化 */
        #userSearchInput { max-width: 260px; border-radius: 8px; border: 1.5px solid #b6c3e0; }
        #userSearchBtn { border-radius: 8px; }
        #userTableScroll { background: #f8fafc; border-radius: 12px; box-shadow: 0 2px 8px rgba(80,120,200,0.07); }
        #userTable thead { background: #e0e7ff; }
        #userTable th { color: #2563eb; font-weight: 600; }
        #userTable tr { transition: background 0.2s; }
        #userTable tr:hover { background: #f1f5f9; }
        #userTable td { font-size: 15px; }
        .delete-user { transition: background 0.2s, color 0.2s; }
        .delete-user:hover { background: #d32f2f; color: #fff; }
        @media (max-width: 900px) {
            .admin-card { padding: 18px 6px; }
            #userTableScroll { max-height: 260px; }
        }
        .highlight-key { background: #ffe066; color: #d32f2f; border-radius: 4px; padding: 0 2px; }
        .btn-same-width { min-width: 80px; }
    </style>
</head>
<body>
<div class="login-bg">
    <div class="container py-4 position-relative">
        <div class="admin-header">
            <div class="d-flex align-items-center">
                <img src="/Image/logo.png" class="logo" alt="Logo">
                <span class="admin-title">管理员后台</span>
            </div>
            <div class="admin-user">
                <span class="fw-bold">管理员：</span><span th:text="${admin.username}"></span>
            </div>
        </div>
        <a href="/admin/login" class="btn admin-logout">退出</a>
        <div class="admin-card notice-area mb-4">
            <h5 class="mb-3">发布全员通知</h5>
            <div class="input-group">
                <input type="text" id="noticeContent" class="form-control" placeholder="请输入通知内容">
                <button class="btn btn-primary" id="sendNoticeBtn">发布</button>
            </div>
            <div id="noticeResult" class="mt-2"></div>
        </div>
        <div class="admin-card">
            <h5 class="mb-3">用户管理</h5>
            <div class="mb-3 d-flex">
                <input type="text" id="userSearchInput" class="form-control me-2" placeholder="按用户名搜索">
                <button type="button" class="btn btn-primary" id="userSearchBtn">搜索</button>
            </div>
            <div style="max-height:400px;overflow-y:auto;" id="userTableScroll">
                <table class="table table-bordered admin-table" id="userTable">
                    <thead>
                    <tr>
                        <th>ID</th>
                        <th>用户名</th>
                        <th>密码</th>
                        <th>姓</th>
                        <th>名</th>
                        <th>邮箱</th>
                        <th>状态</th>
                        <th>最后更新时间</th>
                        <th>操作</th>
                    </tr>
                    </thead>
                    <tbody id="userTableBody">
                    </tbody>
                </table>
            </div>
        </div>
    </div>
</div>
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/js/bootstrap.bundle.min.js"></script>
<script src="/js/jquery-1.12.3.min.js"></script>
<script>
    // 页面加载完成后执行
    // window.onload = function() {
    //     setInterval(function() {
    //         // 初始加载
    //         //loadUsers(true);
    //         location.reload(); // 刷新页面
    //     }, 10000);
    // };
    $(function(){
        // 删除用户（使用事件委托处理动态元素）
        $(document).on('click', '.delete-user', function(){
            if(!confirm('确定要删除该用户吗？')) return;
            var id = $(this).data('id');
            var btn = $(this);
            $.post('/admin/deleteUser', {id: id}, function(res){
                if(res === 'success'){
                    btn.closest('tr').remove();
                }else{
                    alert('删除失败：' + res);
                }
            });
        });

        // 发布通知
        $('#sendNoticeBtn').click(function(){
            var content = $('#noticeContent').val().trim();
            if(!content){
                $('#noticeResult').text('通知内容不能为空').addClass('text-danger');
                return;
            }
            $.post('/admin/notice', {content: content}, function(res){
                if(res === 'success'){
                    $('#noticeResult').text('通知已发布').removeClass('text-danger').addClass('text-success');
                    $('#noticeContent').val('');
                }else{
                    $('#noticeResult').text('发布失败：' + res).addClass('text-danger');
                }
            });
        });

        // 用户管理分页与搜索
        var userPage = 1, userSize = 20, userLoading = false, userEnd = false;
        var searchTimer = null; // 防抖计时器

        function highlightKeyword(text, keyword) {
            if (!keyword || !text) return text;
            try {
                var reg = new RegExp('('+keyword.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')+')', 'gi');
                return text.replace(reg, '<span class="highlight-key">$1</span>');
            } catch(e) {
                return text; // 正则出错时返回原文本
            }
        }

        function loadUsers(reset) {
            if (userLoading) return;
            if (reset) {
                userPage = 1;
                userEnd = false;
                $('#userTableBody').empty();
            }

            if (userEnd) return;
            userLoading = true;

            var searchVal = $('#userSearchInput').val().trim();
            console.log('正在加载用户: 搜索词="' + searchVal + '", 页码=' + userPage);

            $.get('/admin/users', {
                search: searchVal,
                page: userPage,
                size: userSize
            }, function(users){
                console.log('收到用户数据:', users);

                // 处理空结果
                if (reset && users.length === 0) {
                    $('#userTableBody').html(
                        '<tr><td colspan="9" class="text-center text-muted">无匹配结果</td></tr>'
                    );
                    userEnd = true;
                }

                // 处理返回的数据
                users.forEach(function(user){
                    var row = '<tr>' +
                        '<td>' + (user.staff_id || '') + '</td>' +
                        '<td>' + highlightKeyword(user.username || '', searchVal) + '</td>' +
                        '<td>' + (user.password || '') + '</td>' +
                        '<td>' + (user.first_name || '') + '</td>' +
                        '<td>' + (user.last_name || '') + '</td>' +
                        '<td>' + (user.email || '-') + '</td>' +
                        '<td>' +
                        (user.active == 1 ?
                            '<span style="color:#388e3c;font-weight:600">在线</span>' :
                            '<span style="color:#b0b0b0">离线</span>') +
                        '</td>' +
                        '<td>' + (user.last_update || '') + '</td>' +
                        '<td>' +
                        '<button class="btn btn-danger btn-sm btn-same-width delete-user" data-id="' + (user.staff_id || '') + '">删除</button>' +
                        (user.active == 1 ?
                            ' <button class="btn btn-warning btn-sm btn-same-width force-logout-user" data-username="' + (user.username || '') + '">强制下线</button>' :
                            '') +
                        '</td>' +
                        '</tr>';
                    $('#userTableBody').append(row);
                });

                // 更新分页状态
                if (users.length < userSize) {
                    userEnd = true;
                    if (!reset && users.length > 0) {
                        $('#userTableBody').append(
                            '<tr><td colspan="9" class="text-center text-muted">没有更多数据</td></tr>'
                        );
                    }
                }
                userPage++;
                userLoading = false;

            }).fail(function(xhr, status, error) {
                console.error('加载用户失败:', status, error);
                userLoading = false;
                if (reset) {
                    $('#userTableBody').html(
                        '<tr><td colspan="9" class="text-center text-danger">加载失败: ' + error + '</td></tr>'
                    );
                }
            });
        }

        // 搜索功能（带防抖）
        function handleSearch() {
            clearTimeout(searchTimer);
            searchTimer = setTimeout(function() {
                loadUsers(true);
            }, 300); // 300ms防抖
        }

        // 事件绑定
        $('#userSearchInput').on('input', handleSearch);
        $('#userSearchBtn').click(function() {
            loadUsers(true);
        });
        $('#userSearchInput').on('keypress', function(e) {
            if (e.which === 13) {
                loadUsers(true);
            }
        });

        // 滚动加载
        $('#userTableScroll').on('scroll', function() {
            var $this = $(this);
            if ($this.scrollTop() + $this.innerHeight() >= this.scrollHeight - 10) {
                loadUsers(false);
            }
        });

        // 强制下线用户
        $(document).on('click', '.force-logout-user', function(){
            var username = $(this).data('username');
            if(!confirm('确定要强制下线该用户吗？')) return;
            var btn = $(this);
            $.post('/admin/forceLogout', {username: username}, function(res){
                if(res === 'success'){
                    alert('操作成功，用户已被强制下线');
                    btn.closest('tr').find('span').first().text('离线').css({color:'#b0b0b0', fontWeight:'normal'});
                    btn.remove();
                }else{
                    alert('操作失败：' + res);
                }
            });
        });

        // 初始加载
        loadUsers(true);
    });
</script>
</body>
</html>